package com.i_art_engineer.meigong.activity;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.i_art_engineer.meigong.AppConsts;
import com.i_art_engineer.meigong.AppContext;
import com.i_art_engineer.meigong.R;
import com.i_art_engineer.meigong.adapter.ImageThumbListAdapter;
import com.i_art_engineer.meigong.adapter.JigsawSelectorListAdapter;
import com.i_art_engineer.meigong.base.FullScreenActivity;
import com.i_art_engineer.meigong.photo.cache.ACache;
import com.i_art_engineer.meigong.photo.jigsaw.JigsawLinearLayout;
import com.i_art_engineer.meigong.photo.jigsaw.JigsawModelLayout;
import com.i_art_engineer.meigong.photo.jigsaw.JigsawParser;
import com.i_art_engineer.meigong.photo.jigsaw.JigsawTemplate;
import com.i_art_engineer.meigong.photo.jigsaw.JigsawTemplateEntity;
import com.i_art_engineer.meigong.photo.jigsaw.JigsawType;
import com.i_art_engineer.meigong.util.DeviceUtils;
import com.i_art_engineer.meigong.util.FileUtils;
import com.i_art_engineer.meigong.widget.DragLinearView;
import com.i_art_engineer.meigong.widget.HorizontalListView;
import com.i_art_engineer.meigong.widget.SquareFrameLayout;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXImageObject;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * 图片编辑界面
 */
public class JigsawActivity extends FullScreenActivity {

    private static final int PHOTO_PICKED_WITH_DATA = 1000;
    // 拼图为正方形，宽高比为1.0f
    private static final float JIGSAW_MODEL_RATIO = 1.0f;

    private static int MAX_SELECTED_NUM = 2;  //最多选择两张照片

    public ArrayList<String> mPhotos;

    public ArrayList<String> mSelected = new ArrayList<>();

    public static final String EXTRA_JIGSAW_IMAGES = "jigsaw_images";

    private JigsawModelLayout jigsawArea;

    private RelativeLayout jigsawAreaParent;

    //当前模版类型
    private JigsawType jigsawType;
    private JigsawTemplateEntity mEntity;

    private LinearLayout mThumArea, mJigsawArea;

    private List<JigsawTemplateEntity> mEntities;

    private LayoutInflater flater;

    private int jigsawParentWidth, jigsawParentHeight;
    private ACache mCache= AppContext.instance().getmCache();
    public static final String PROCESSED="processed";
    private String mCurPath=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jigsaw);

        flater = LayoutInflater.from(this);
        res = this.getResources();
        // 加载图像列表,默认选择一张
        Intent intent = getIntent();
        mPhotos = intent.getStringArrayListExtra(EXTRA_JIGSAW_IMAGES);
        mSelected.add(mPhotos.get(0));

        initViews();
    }

    @Override
    public void onBackPressed() {
        if (jigsawArea.getShowSelectedState()) {
            jigsawArea.setShowSelectedState(false);
        } else {
            super.onBackPressed();
        }
    }

    public void initViews() {
        // 获取父类布局
        JigsawLinearLayout rootLayout = (JigsawLinearLayout) findViewById(R.id.jigsaw_root);
        rootLayout.setOnSelectedStateChangedListener(new JigsawLinearLayout.OnSelectedStateChangedListener() {
            @Override
            public void onSelectedStateChanged() {
                // 这里设置隐藏选中边框，不显示组件
                jigsawArea.setShowSelectedState(false);
            }
        });

        jigsawArea = (JigsawModelLayout) findViewById(R.id.single_jigsaw_area);

        //图片列表
        initThumbViews(mPhotos,false);

        // 样式区域
        mJigsawArea = (LinearLayout) findViewById(R.id.ll_jigsaw_list);
        initJigsawViews();
        SetDisplayWidthAndHeight(jigsawArea);
        //编辑区域
        jigsawAreaParent = (RelativeLayout) findViewById(R.id.single_jigsaw_parent);
        final ViewTreeObserver observer = jigsawAreaParent.getViewTreeObserver();
        observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                jigsawParentWidth = jigsawAreaParent.getMeasuredWidth();
                jigsawParentHeight = jigsawAreaParent.getMeasuredHeight();
                jigsawAreaParent.getViewTreeObserver().removeOnPreDrawListener(this);
                redrawJigsawArea();
                return true;
            }
        });

        // ActionBar区域
        findViewById(R.id.btn_back).setOnClickListener(listener);
        findViewById(R.id.tv_PhotoSave).setOnClickListener(listener);
        findViewById(R.id.iv_wrong).setOnClickListener(listener);
        findViewById(R.id.iv_right).setOnClickListener(listener);

    }
    private Resources res;
    int imgh=0;
    /**
     * 初始化缩略图
     */
    public void initThumbViews(ArrayList<String> paths, boolean isAppend) {
        mThumArea = (LinearLayout) findViewById(R.id.ll_photos_thumb_list);
//        int height = getResources().getDimensionPixelSize(R.dimen.photo_action_bar_height);
        int height = res.getDimensionPixelSize(R.dimen.photo_action_bar_thumb_height);
         imgh = res.getDimensionPixelSize(R.dimen.photo_action_bar_thumb_img_height);
     //   int imgh = getResources().getDimensionPixelSize(R.dimen.photo_action_bar_thumb_img_height);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(height, height);
//        lp.setMargins(0, 10, 10, 10);
        lp.setMargins(0, 5, 0, 5);
        for (int i = 0; i < paths.size(); i++) {
            SquareFrameLayout thumb = (SquareFrameLayout) flater.inflate(R.layout.list_item_thumb, null);
            thumb.setTag(paths.get(i));
            thumb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String file = (String) v.getTag();
                    View mask = v.findViewById(R.id.mask);
                    boolean isChanged = false;
                    if (mSelected.contains(file)) {
                        if (mSelected.size() > 1) {
                            mask.setVisibility(View.GONE);
                            mSelected.remove(file);
                            isChanged = true;
                        } else {
                            Toast.makeText(JigsawActivity.this, "最少选择一张图片", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        //不能超过最大数
                        if (mSelected.size() < MAX_SELECTED_NUM) {
                            mask.setVisibility(View.VISIBLE);
                            mSelected.add(file);
                            isChanged = true;
                        } else {
                            Toast.makeText(JigsawActivity.this, "最多只能选择" + MAX_SELECTED_NUM + "张图片", Toast.LENGTH_SHORT).show();
                        }
                    }
                    if (isChanged) initJigsawViews();
                    //((TextView)v).setTextColor(res.getColor(R.color.photo_text_font_selected_color));
                    //Toast.makeText(PhotoEditorActivity.this, "点击字体" + defaultFont, Toast.LENGTH_SHORT).show();
                }
            });
            ImageView img = (ImageView) thumb.findViewById(R.id.image);
            // 显示图片

           Bitmap processed=getBitmapFromCache(paths.get(i));
            if(processed!=null)
            {
                Picasso.with(this)
                        .load(mCache.getFile(mCurPath))
                        .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
                        .placeholder(R.drawable.tu)
                        .resize(imgh-8, imgh)
                        .into(img);
            }else
            {
                Picasso.with(this)
                        .load(new File(paths.get(i)))
                        .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
                        .placeholder(R.drawable.tu)
                        .resize(imgh-8, imgh)
                        .into(img);
            }
            if (mSelected.contains(paths.get(i))) {
                View view = thumb.findViewById(R.id.mask);
                view.setVisibility(View.VISIBLE);
            }
            thumb.setLayoutParams(lp);
            if (isAppend) {
                mThumArea.addView(thumb, mPhotos.size());
                mPhotos.add(paths.get(i));
            } else
                mThumArea.addView(thumb);
        }

        if(!isAppend) {
            final LinearLayout thumb = (LinearLayout) flater.inflate(R.layout.list_item_photo, null);
            ImageView img = (ImageView) thumb.findViewById(R.id.image);
            View mask = thumb.findViewById(R.id.mask);
            ImageView del = (ImageView) thumb.findViewById(R.id.delmark);
            thumb.setTag("");
            thumb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(JigsawActivity.this, PhotoSelectorActivity.class);
                    // 是否显示拍摄图片
                    intent.putExtra(PhotoSelectorActivity.EXTRA_SHOW_CAMERA, true);
                    // 最大可选择图片数量
                    intent.putExtra(PhotoSelectorActivity.EXTRA_SELECT_COUNT, AppConsts.PHOTO_SELECTOR_IMAGE_MAX_NUM);
                    // 选择模式
                    intent.putExtra(PhotoSelectorActivity.EXTRA_SELECT_MODE, PhotoSelectorActivity.MODE_MULTI);
                    // 已选择图片
                    intent.putExtra(PhotoSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, mPhotos);
                    intent.putExtra(PhotoSelectorActivity.EXTRA_APPEND_IMAGES_MODE, true);
                    startActivityForResult(intent, AppConsts.ACTIVITY_REQUEST_PHOTO_AGAIN_SELECTOR_IMAGE);
                }
            });
            mask.setVisibility(View.GONE);
            del.setVisibility(View.GONE);
            // 显示图片
            Picasso.with(this)
                    .load(R.drawable.tianjia)
                    .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
                    .placeholder(R.drawable.tu)
                    .resize(imgh, imgh)
                    .into(img);
            thumb.setLayoutParams(lp);
            mThumArea.addView(thumb);
        }

    }
    Transformation transformation = new Transformation() {

        @Override
        public Bitmap transform(Bitmap source) {

            if(source.getWidth()==0){
                return source;
            }

            //如果图片小于设置的宽度，则返回原图
     {
                //如果图片大小大于等于设置的宽度，则按照设置的宽度比例来缩放

                {
                    Bitmap result = Bitmap.createScaledBitmap(source, imgh-8, imgh, false);
                    if (result != source) {
                        // Same bitmap is returned if sizes are the same
                        source.recycle();
                    }
                    return result;
                }

            }

        }

        @Override
        public String key() {
            return "transformation" + " desiredWidth";
        }
    };
    public Bitmap getBitmapFromCache(String path)
    {
        mCurPath=PROCESSED+path;
        Bitmap ret=mCache.getAsBitmap(PROCESSED+path);
        if(ret==null)
        {
            ret=mCache.getAsBitmap(path);
            mCurPath=path;
        }
//        else
//         saveImageToGallery(ret);
        return ret;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppConsts.ACTIVITY_REQUEST_PHOTO_AGAIN_SELECTOR_IMAGE) {
            if (resultCode == RESULT_OK) {
                //获取新增的图片
                ArrayList<String> newImgs = data.getStringArrayListExtra(PhotoSelectorActivity.EXTRA_RESULT);
                //弹出图片编辑界面
//                LinkedList<DragLinearView.ImageTagElement> imageTagElementList = new LinkedList<>();
//                for (int i = 0; i < newImgs.size(); i++) {
//                    imageTagElementList.add(new DragLinearView.ImageTagElement(
//                            BitmapFactory.decodeFile(newImgs.get(i)),
//                            newImgs.get(i)
//                    ));
//                }
                //TODO:
                initThumbViews(newImgs, true);
                //mPhotosView.addMutilItemView(imageTagElementList, false);
                //photo_paths.addAll(newImgs);
            }
        }
    }


    public void initJigsawViews() {
        // 刷新拼图列表
//        jigsawType = JigsawTemplate.getJigsawType(mSelected.size());
        jigsawType = JigsawTemplate.getJigsawType(2);
        mEntities = JigsawParser.getInstance(JigsawActivity.this).getEntityList(jigsawType);
        mEntity = mEntities.get(0);
        jigsawArea.setImagePathList(mSelected);
        jigsawArea.setTemplateEntity(mEntity);
        redrawJigsawArea();
        List<Integer> tplImgs = new ArrayList<>();
        for (JigsawTemplateEntity entity : mEntities) {
            switch (entity.getId()) {
                case 1:
                    tplImgs.add(R.drawable.pintu_no1);
                    break;
                case 2:
                    tplImgs.add(R.drawable.pintu_no1);
                    break;
                case 3:
                    tplImgs.add(R.drawable.pintu_no2);
                    break;
                case 4:
                    tplImgs.add(R.drawable.pintu_lr);
                    break;
                case 5:
                    tplImgs.add(R.drawable.pintu_tb);
                    break;
                default:
                    tplImgs.add(R.drawable.pintu_tb);
                    break;
            }
        }
        mJigsawArea.removeAllViews();
        int height = getResources().getDimensionPixelSize(R.dimen.jigsaw_list_height) - 20;
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(height, height);
        lp.setMargins(0, 10, 10, 10);
        for (int i = 0; i < tplImgs.size(); i++) {
            SquareFrameLayout thumb = (SquareFrameLayout) flater.inflate(R.layout.list_item_jigsaw, null);
            thumb.setTag(Integer.valueOf(i));
            thumb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //i序列就是加载
                    int indx = (Integer) v.getTag();
                    mEntity = getEntity(indx);
                    if (mEntity != null) {
                        jigsawArea.setImagePathList(mSelected);
                        //选择加载模板
                        jigsawArea.setTemplateEntity(mEntity);
                        redrawJigsawArea();
                    }

                }
            });
            ImageView img = (ImageView) thumb.findViewById(R.id.image);
            // 显示图片
            Picasso.with(this)
                    .load(tplImgs.get(i))
                    .placeholder(R.drawable.tu)
                    .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
                    .resize(height, height)
                    .into(img);
            thumb.setLayoutParams(lp);
            mJigsawArea.addView(thumb);
        }
    }

    /**
     * 获取单个SlotView的Entity
     *
     * @param position
     * @return
     */
    public JigsawTemplateEntity getEntity(int position) {
        if (position < 0 || position >= mEntities.size()) {
            return null;
        }

        return mEntities.get(position);
    }

    private void redrawJigsawArea() {
        if (0 != jigsawParentWidth && 0 != jigsawParentHeight) {
            float ratio = ((float) jigsawParentWidth) / jigsawParentHeight;

            int modelAreaWidth;
            int modelAreaHeight;

            if (JIGSAW_MODEL_RATIO > ratio) {
                modelAreaWidth = jigsawParentWidth;
                modelAreaHeight = (int) (jigsawParentWidth / JIGSAW_MODEL_RATIO);
            } else {
                modelAreaHeight = jigsawParentHeight;
                modelAreaWidth = (int) (modelAreaHeight * JIGSAW_MODEL_RATIO);
            }

            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(modelAreaWidth, modelAreaHeight);
            params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.CENTER_IN_PARENT);
            jigsawArea.setLayoutParams(params);

            jigsawArea.reDraw(modelAreaWidth, modelAreaHeight);
        }
    }

    public void SetDisplayWidthAndHeight( JigsawModelLayout jigsawArea)
    {
        Display display = this.getWindowManager().getDefaultDisplay();
        jigsawArea.setDisplay_width(display.getWidth());
        jigsawArea.setGetDisplay_height(display.getHeight());
    }
    public boolean saveImageToGallery(Bitmap bm)
    {
        File dir=new File(Environment.getExternalStorageDirectory(),"processImage");
        if(!dir.exists())
        {
            dir.mkdir();
        }
        String filename=System.currentTimeMillis()+".jpg";
        File file=new File(dir,filename);
        try
        {
            FileOutputStream fos=new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.JPEG,100,fos);
            fos.flush();
            fos.close();
        }catch (FileNotFoundException e)
        {
            e.printStackTrace();
            return false;
        }catch (IOException e)
        {
            e.printStackTrace();
            return false;
        }
        //把文件插入系统图库
        try
        {
            MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),filename,null);
        }catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        //更新图库
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.parse("file://"+file.getAbsolutePath())));
        return true;
    }
    /**
     * 保存图片
     *
     * @return
     */
    public boolean saveBitmapToDCIM() {
        Bitmap bmp = Bitmap.createBitmap(jigsawArea.getWidth(), jigsawArea.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bmp);
        jigsawArea.draw(canvas);
        ContentValues values = new ContentValues(8);
        String newname = DateFormat.format("yyyy-MM-dd kk.mm.ss", System.currentTimeMillis()).toString();
        values.put(MediaStore.Images.Media.TITLE, newname);//名称，随便
        values.put(MediaStore.Images.Media.DISPLAY_NAME, newname);
        values.put(MediaStore.Images.Media.DESCRIPTION, "i美工");//描述，随便
        values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());//图像的拍摄时间，显示时根据这个排序
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");//默认为jpg格式
        values.put(MediaStore.Images.Media.ORIENTATION, 0);

        final String CAMERA_IMAGE_BUCKET_NAME = "/sdcard/dcim/camera";
        final String CAMERA_IMAGE_BUCKET_ID = String.valueOf(CAMERA_IMAGE_BUCKET_NAME.hashCode());
        File parentFile = new File(CAMERA_IMAGE_BUCKET_NAME);
        String name = parentFile.getName().toLowerCase();

        values.put(MediaStore.Images.ImageColumns.BUCKET_ID, CAMERA_IMAGE_BUCKET_ID);//id
        values.put(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME, name);

        // 先得到新的URI
        Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

        try {
            //写入数据
            OutputStream outStream = getContentResolver().openOutputStream(uri);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
            outStream.close();
        } catch (Exception e) {
            Log.e("SaveBitmap", "exception while writing image", e);
            return false;
        }
        return true;
    }

    public View.OnClickListener listener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_back:
                    finish();
                    break;
                case R.id.tv_PhotoSave:
                case R.id.iv_right:
                    //保存当前的到相机内
                    Bitmap bmp = Bitmap.createBitmap(jigsawArea.getWidth(), jigsawArea.getHeight(), Bitmap.Config.ARGB_8888);
                    Canvas canvas = new Canvas(bmp);
                    jigsawArea.draw(canvas);
                    if (saveImageToGallery(bmp)) {
                        Toast.makeText(JigsawActivity.this, "图片已保存到相册", Toast.LENGTH_SHORT).show();
                        //分享
                    }
                    else
                        Toast.makeText(JigsawActivity.this, "图片保存失败", Toast.LENGTH_SHORT).show();
                    if(bmp!=null&&!bmp.isRecycled())
                    {
                        bmp.recycle();
                        bmp=null;
                    }
                    break;
                case R.id.iv_wrong:
                    finish();
                    break;
            }
        }

    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(jigsawArea!=null)
        {
            jigsawArea.FreeBitmap();
        }
        System.gc();
    }
}
